<template>
  <div>
    <form @keyup.enter="keyupEvemtFun(snVal)" @submit.prevent style="opacity: 0;">
      <div><el-input v-model.trim="snVal" ref="afinput"></el-input></div>
    </form>
    <el-dialog :title="ruleForm.id ? '编辑出货' : '新增出货'" :visible.sync="isDialogShow" :show-close="false" :destroy-on-close="true" :close-on-click-modal="false" width="50%" custom-class="customWidth">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="1.扫入设备" name="name1" :disabled="ruleForm.id"></el-tab-pane>
        <el-tab-pane label="2.关联信息" name="name2" :disabled="!device_list.length"></el-tab-pane>
      </el-tabs>
      <div style="padding-left: 20px;" v-show="activeName === 'name1'">提示：请先链接扫码枪，扫入的设备将直接展示在下面方框</div>
      <el-row class="data-list" v-show="activeName === 'name1'" style="padding: 15px 20px 0 20px;">
        <el-table :data="device_list" border class="table_box" style="width:100%" height="289">
          <el-table-column prop="sn" label="设备号" align="center"></el-table-column>
          <el-table-column prop="imei" label="IMEI" align="center"></el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <div style="color: #FF0000" @click="delEvemt(scope.$index, scope.row)">删除</div>
            </template>
          </el-table-column>
        </el-table>
        <div style="padding-top: 20px;text-align: right;">当前设备数量：<span style="color: #FF0000;font-size: 18px;">{{device_list.length}}</span>台</div>
      </el-row>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" v-show="activeName === 'name2'" style="padding: 15px 20px 0 20px;">
        <el-form-item label="出货客户:" :label-width="formLabelWidth" prop="customer_id">
          <el-button type="primary" size="small" @click="submitForm(4)">选择</el-button> <span style="padding-left: 20px;">{{unitInfo.name}}</span>
        </el-form-item>
        <el-form-item label="关联接口:" :label-width="formLabelWidth" prop="interface_id">
          <el-button type="primary" size="small" @click="submitForm(5)">选择</el-button> <span style="padding-left: 20px;">{{interfaceObj.name}}</span>
        </el-form-item>
        <el-form-item label="设备型号:" :label-width="formLabelWidth" prop="class_id">
          <el-select v-model="ruleForm.class_id" placeholder="请选择设备型号" style="width: 350px;">
            <el-option v-for="item in classlist" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="维保时间:" :label-width="formLabelWidth" prop="Timepicker">
          <el-date-picker v-model="ruleForm.Timepicker[0]" type="date" size="small"  class="width150" placeholder="请选择时间"></el-date-picker>
          &nbsp;至&nbsp;
          <el-date-picker v-model="ruleForm.Timepicker[1]" type="date" size="small"  class="width150" placeholder="请选择时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="备  注:" :label-width="formLabelWidth" prop="remarks">
          <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" placeholder="请输入备注信息" v-model="ruleForm.remarks" autocomplete="off" style="width: 350px;"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="submitForm(1)">取消</el-button>
        <el-button type="primary" @click="submitForm(2)" v-show="activeName === 'name1'">下一步</el-button>
        <el-button type="primary" @click="submitForm(3)" v-show="activeName === 'name2'">出 货</el-button>
      </div>
    </el-dialog>
    <customers-bounced v-if="iscustomersBounced" @customersBouncedEvemt="customersBouncedEvemt" :unitInfoBounced="unitInfo"></customers-bounced>
    <interface-bounced v-if="isinterfaceBounced" @interfaceBouncedEvemt="interfaceBouncedEvemt" :interfaceData="interfaceObj"></interface-bounced>
  </div>
</template>
<script>
import { vueTimeFormat } from 'src/filter/index'
import customersBounced from 'components/customersBounced.vue'
import interfaceBounced from 'components/interfaceBounced.vue'
import common from 'src/util/common.js'
import {deviceclasslist, shipmentadd, shipmentupdate, deviceinfo} from 'api/txEquipment/index'
let Intervalevemt = null
export default {
  data () {
    return {
      // dateTstart: {
      //   disabledDate: time => {
      //     return (
      //       time.getTime() <= (this.ruleForm.Timepicker[1] || Date.now())
      //     )
      //   }
      // },
      activeName: '',
      dateTend: {
        disabledDate: time => {
          return (
            time.getTime() > Date.now() || time.getTime() < (this.ruleForm.Timepicker[0] || (Date.now() - 8.64e7))
          )
        }
      },
      snVal: '',
      formLabelWidth: '120px',
      formLabelWidth2: '60px',
      rules: {
        customer_id: [
          { required: true, message: '请选择客户', trigger: 'change' }
        ],
        interface_id: [
          { required: true, message: '请选择关联接口', trigger: 'change' }
        ],
        class_id: [
          { required: true, message: '请选择设备型号', trigger: 'change' }
        ],
        Timepicker: [
          { required: true, message: '请选择维保时间', trigger: 'change' }
        ]
      },
      ruleForm: {
        customer_id: '',
        interface_id: '',
        class_id: '',
        Timepicker: [],
        remarks: ''
      },
      isinterfaceBounced: false,
      iscustomersBounced: false,
      isDialogShow: true,
      unitInfo: {id: null, name: null},
      interfaceObj: {id: null, name: null},
      classlist: [],
      device_list: [],
      snIds: [],
      shipmentData: {}
    }
  },
  props: {
    shipmentCopyData: Object
  },
  components: {
    customersBounced,
    interfaceBounced
  },
  created () {
    this.shipmentData = JSON.parse(JSON.stringify(this.shipmentCopyData))
    this.snIds = []
    this.device_list = [] // [{sn: 11, id: 11}, {sn: 12, id: 11}, {sn: 13, id: 11}, {sn: 14, id: 11}, {sn: 15, id: 11}, {sn: 16, id: 11}, {sn: 17, id: 11}]
    deviceclasslist({
      pageSize: 10000,
      pageIndex: 0
    }).then(res => {
      this.classlist = res.data || []
    })
    if (this.shipmentData.id) {
      this.activeName = 'name2'
      this.unitInfo = {id: this.shipmentData.customer_id, name: this.shipmentData.copyDAta.customer_name}
      this.interfaceObj = {id: this.shipmentData.interface_id, name: this.shipmentData.copyDAta.interface_name}
      this.ruleForm = {
        id: this.shipmentData.id,
        customer_id: this.shipmentData.customer_id,
        interface_id: this.shipmentData.interface_id,
        class_id: this.shipmentData.class_id,
        Timepicker: [this.shipmentData.start_time, this.shipmentData.end_time],
        remarks: this.shipmentData.remarks
      }
    } else {
      this.activeName = 'name1'
      this.$nextTick(() => {
        this.IntervalFun()
      })
    }
  },
  methods: {
    delEvemt (index, data) {
      console.log(data)
      this.$confirm('是否删除该设备？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.snIds.splice(index, 1)
        this.device_list.splice(index, 1)
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      })
    },
    IntervalFun () {
      this.$refs.afinput && this.$refs.afinput.focus()
      Intervalevemt = setInterval(() => {
        if (this.activeName === 'name1') {
          this.$refs.afinput && this.$refs.afinput.focus()
        }
      }, 600)
    },
    handleClick (tab, event) {
      if (tab.name === 'name1') {
        this.$nextTick(() => {
          this.IntervalFun()
        })
      } else {
        clearInterval(Intervalevemt)
      }
    },
    keyupEvemtFun (obj) {
      this.snVal = ''
      if (this.snIds.indexOf(obj) === -1) {
      // console.log(123465, obj, 'SYQTM3Z100000778')
        deviceinfo({sn: obj}).then(res => {
          console.log(123465, res.data)
          if (res.data) {
            if (this.snIds.indexOf(res.data.sn) === -1) {
              this.snIds.push(res.data.sn)
              this.device_list.push(res.data)
            } else {
              this.$message({ message: '该设备已扫描，请查看列表', type: 'warning' })
            }
          }
        })
      } else {
        this.$message({ message: '该设备已扫描，请查看列表', type: 'warning' })
      }
    },
    vueTimeFormats (value) {
      return vueTimeFormat(value, 'yyyy-MM-dd')
    },
    submitForm (num) {
      switch (num) {
        case 1:
          this.$emit('addShipmentEvem', {type: 2})
          break
        case 2:
          if (this.device_list.length) {
            this.activeName = 'name2'
          } else {
            this.$message.error('请先扫码')
          }
          break
        case 3:
          this.$refs['ruleForm'].validate((valid) => {
            if (valid) {
              let obj = JSON.parse(JSON.stringify(this.ruleForm))
              if (this.ruleForm.Timepicker.length && this.ruleForm.Timepicker[0] && this.ruleForm.Timepicker[1]) {
                obj.start_time = this.vueTimeFormats(parseInt(common.div((new Date(this.ruleForm.Timepicker[0])).getTime(), 1000)))
                obj.end_time = this.vueTimeFormats(parseInt(common.div((new Date(this.ruleForm.Timepicker[1])).getTime(), 1000)))
              }
              obj.Timepicker = undefined
              if (!obj.id) {
                let deviceList = []
                this.device_list.forEach(element => {
                  deviceList.push(element.sn)
                })
                obj.device_list = deviceList
              }
              var evemtFuns = obj.id ? shipmentupdate : shipmentadd
              evemtFuns(obj).then(res => {
                this.$message({
                  message: `${obj.id ? '编辑' : '出货'}出货成功`,
                  type: 'success'
                })
                this.$emit('addShipmentEvem', {type: 1})
              })
            }
          })
          break
        case 4:
          if (!this.unitInfo.id) {
            this.unitInfo = {id: null, name: null}
          }
          this.iscustomersBounced = true
          break
        case 5:
          if (!this.interfaceObj.id) {
            this.interfaceObj = {id: null, name: null}
          }
          this.isinterfaceBounced = true
          break
      }
    },
    customersBouncedEvemt (obj) {
      if (obj.type === 1) {
        this.unitInfo = obj.unitInfo
        this.ruleForm.customer_id = obj.unitInfo.id
        this.iscustomersBounced = false
      } else {
        this.iscustomersBounced = false
      }
      this.$refs.ruleForm.validateField('customer_id')
    },
    interfaceBouncedEvemt (obj) {
      if (obj.type === 1) {
        this.interfaceObj = obj.interfaceObj
        this.ruleForm.interface_id = obj.interfaceObj.id
        this.isinterfaceBounced = false
      } else {
        this.isinterfaceBounced = false
      }
      this.$refs.ruleForm.validateField('interface_id')
    }
  }
}
</script>
<style lang="less">
  .customWidth{
    min-width: 560px;
  }
</style>
